<template>
  <div id="myamap-line-page" :style="{
    width:'100%',
    height: (this.getWinSize().height-43-this.getSafeArea().top)+'px',
    // paddingTop:(43-this.getSafeArea().top)+'px',
  }">
    <div class="page-title page-title-white" :style="{
      top:(this.getSafeArea().top)+'px'
    }">
      <div id="back-button" @click="$router.back()">
        <i href="javascript:void(0)" class="el-icon-arrow-left"></i>
      </div>
      <span>路线规划</span>
      <el-button type="primary" style="position: absolute; right: 5px; top: 5px;" @click="openNavigation">打开地图导航
      </el-button>

      <!--      <el-checkbox style="position: absolute; right: 5px; top: 5px;" v-model="changeStartPoint" label="修改出发点"-->
      <!--                   border></el-checkbox>-->
    </div>
    <div id="map-content" style="position: relative;" :style="{
      top: (43+this.getSafeArea().top)+'px',
      width:'100%',
      height: (getWinSize().height-40-this.getSafeArea().top)+'px'
    }"></div>
    <div id="panel"></div>
  </div>
</template>


<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import MapTools from '../tools/MapTools'

export default {
  name: 'MyAMap',
  data: function () {
    return {
      map: null,
      driving: null,
      addressLoading: false,
      topSize: (43 + this.getSafeArea().top),
      keywords: '',
      location: [],
      provinceCityCounty: '',
      isSelecting: false,
      searchResult: false,
      searchResultStatus: 0,
      changeStartPoint: false
    }
  },
  watch: {
    changeStartPoint: function () {
      if (this.changeStartPoint) {

      }
    }
  },
  mounted () {
    this.initParams(this.initMap)
  },
  methods: {
    // 导航 会打开导航菜单供用户选择，都是打开内置地图
    openNavigation () {
      let $this = this
      var endLocation = this.$route.query.endLocation.split(',')
      //方法1


      // 目的地名称
      let name = this.$route.query.addressName
      let url = '' // app url
      let webUrl = '' // web url 用来为用户未安装导航软件时打开浏览器所使用url
      var mapArr=[
        {title: '高德地图'},
        {title: '百度地图'},
        // { title: "腾讯地图" },
      ]
      plus.nativeUI.actionSheet(
        {
          //选择菜单
          title: '选择地图应用',
          cancel: '取消',
          buttons: mapArr, // 可选的地图类型
        },
        (e) => {
          // 判断用户选择的地图
          var originLocation = [$this.location[1],$this.location[0]]
          var destinationLocation = [endLocation[1],endLocation[0]]
          var mapSoftName=mapArr[e.index-1].title
          switch (e.index) {
            // 高德地图
            case 1:
              if (plus.os.name === 'Android') {
                url = `androidamap://navi?sourceApplication=可可商城&poiname=${name}&keywords=${name}&lat=${destinationLocation[0]}&lon=${destinationLocation[1]}&dev=1&style=2`
              } else {
                url = `iosamap://navi?sourceApplication=可可商城&poiname=${name}&keywords=${name}&lat=${destinationLocation[0]}&lon=${destinationLocation[1]}&dev=1&style=2`
              }
              url = `amapuri://route/plan/?did=&dlat=${destinationLocation[0]}&dlon=${destinationLocation[1]}&dname=${name}&dev=0&t=0`
              break
            // 百度地图
            case 2:
              var baiduOriginLocation=MapTools.gcj02tobd09(originLocation[0],originLocation[1])
              baiduOriginLocation=baiduOriginLocation.join(',')
              var baiduDestinationLocation=MapTools.gcj02tobd09(destinationLocation[0],destinationLocation[1])
              baiduDestinationLocation=baiduDestinationLocation.join(',')
              if (plus.os.name === 'Android') {
                url = `baidumap://map/direction?origin=${baiduOriginLocation}&destination=${baiduDestinationLocation}&coord_type=bd09ll&mode=driving&src=andr.baidu.openAPIdemo`
              } else {
                url = `baidumap://map/direction?origin=${baiduOriginLocation}&destination=${baiduDestinationLocation}&coord_type=bd09ll&mode=driving&src=ios.baidu.openAPIdemo`
              }
              break
            // case 3:
            //   url =
            //     `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=腾讯申请的key`
            //   break
            default:
              webUrl = `https://uri.amap.com/marker?position=${destinationLocation[1]},${destinationLocation[0]}&name=${name}&src=mypage&coordinate=gaode`
              break
          }
          // 如果选中
          if (url !== '') {
            url = encodeURI(url)
            // 打开 app 导航
            plus.runtime.openURL(url, (err) => {
              // 失败回到
              // 如果失败则说明未安装 直接 打开网页版进行导航
              // 毕竟用户可能没有安装app但一定安装的有浏览器
              plus.nativeUI.toast('当前地图软件: 【'+mapSoftName+'】，未安装使用浏览器【高德地图】查看')
              plus.runtime.openURL(webUrl)
            })
          }else{
            plus.nativeUI.toast('当前地图软件: 【'+mapSoftName+'】，未安装使用浏览器【高德地图】查看')
            plus.runtime.openURL(webUrl)
          }
        }
      )
      //方法2
      // uni.openLocation({
      //   latitude: 31.975258,
      //   longitude: 118.769032,
      //   name: '想去的地方',
      //   success () {
      //     console.log('success')
      //   },
      // })
    },
    onChangeStartPoint: function () {
    },
    initParams: function (callback) {
      let $this = this
      if (typeof plus === 'undefined') {
        $this.location = $this.CurrUser.getLocation().split(',')
        callback()
        return
      }
      plus.geolocation.getCurrentPosition(function (p) {
        // let tmpLocation = p.coords.longitude + ',' + p.coords.latitude
        // $this.location = [p.coords.longitude, p.coords.latitude]
        var wgs84togcj02Location = MapTools.wgs84togcj02(p.coords.longitude,p.coords.latitude)
        $this.location=wgs84togcj02Location
        console.log('wgs84togcj02Location',wgs84togcj02Location)
        // console.log('获取到当前定位是: ', tmpLocation)
        // $this.setLocationCity(tmpLocation)
        callback()
      }, function (e) {
        plus.nativeUI.toast('获取位置失败，请检查权限是否开启')
        // plus('Geolocation error: ' + e.message);
      })
      /* plus.nativeUI.confirm('请选择您出发点位置?', function (e) {
        if (e.index === 0) {
          plus.geolocation.getCurrentPosition(function (p) {
            let tmpLocation = p.coords.longitude + ',' + p.coords.latitude
            $this.location = [p.coords.longitude, p.coords.latitude]
            // console.log('获取到当前定位是: ', tmpLocation)
            // $this.setLocationCity(tmpLocation)
            callback()
          }, function (e) {
            plus.nativeUI.toast('获取位置失败，请检查权限是否开启')
            // plus('Geolocation error: ' + e.message);
          })
        }
        if (e.index === 1) {
          $this.location = $this.CurrUser.getLocation().split(',')
          callback()
        }
      }, '系统提示', ['当前实时位置', '已保存位置']) */

    },
    searchLine: function (startLocation) {
      let $this = this
      // console.log('startLocation: '+startLocation)
      var endLocation = $this.$route.query.endLocation.split(',')
      $this.driving.search(new AMap.LngLat(startLocation[0], startLocation[1]), new AMap.LngLat(endLocation[0], endLocation[1]), function (status, result) {
        // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
        if (status === 'complete') {
          console.log('绘制驾车路线完成')
        } else {
          console.log('获取驾车数据失败：' + result)
        }
      })
    },

    // 初始化地图
    initMap () {
      let $this = this
      AMapLoader.load({
        key: '60ad93df4245a24c965620376f646582',                                 // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0',                                                          // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Driving'],                       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        $this.map = new AMap.Map('map-content', {  //设置地图容器id
          viewMode: '3D',    //是否为3D地图模式
          zoom: 11,           //初始化地图级别
          center: $this.location, //初始化地图中心点位置
        })

        $this.map.on('click', function (e) {
          if ($this.changeStartPoint) {
            var currPointLocation = [e.lnglat.getLng(), e.lnglat.getLat()]
            // 清除线路,重新绘制
            $this.driving.clear()
            $this.searchLine(currPointLocation)
            $this.changeStartPoint = false
            $this.$forceUpdate()
          }
        })

        // 获取输入提示信息
        /*  AMap.plugin('AMap.Driving', function() {
           var driving = new AMap.Driving({
             // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
             policy: AMap.DrivingPolicy.LEAST_TIME
           })

           var startLngLat = [108.905172,34.124914]
           var endLngLat = [108.934376,34.201023]

           driving.search(startLngLat, endLngLat, function (status, result) {
             // 未出错时，result即是对应的路线规划方案
           })
         }) */

        $this.driving = new AMap.Driving({
          map: $this.map,
          panel: 'panel'
        })
        // var startLocation=$this.$route.query.startLocation.split(',')
        var startLocation = $this.location

        // 根据起终点经纬度规划驾车导航路线
        // alert('startLocation: '+startLocation)
        $this.searchLine(startLocation)

      }).catch(e => {
        console.log(e)
      })
    }
  }
}
</script>

<style>
#myamap-line-page {
}

#myamap-line-page > .page-title {
  position: absolute;
  top: 0px;
  width: 100%;
  font-size: 16px;
  background: #FFFFFF
}

#panel {
  display: none;
  position: fixed;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 40px;
  left: 0px;
  width: 180px;
}

#panel .amap-call {
  background-color: #009cf9;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

#panel .amap-lib-driving {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  overflow: hidden;
}
</style>
